package com.atguigu.lease.web.app.controller.agreement;


import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.LeaseAgreement;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.app.service.LeaseAgreementService;
import com.atguigu.lease.web.app.vo.agreement.AgreementDetailVo;
import com.atguigu.lease.web.app.vo.agreement.AgreementItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/app/agreement")
@Tag(name = "租约信息")
public class LeaseAgreementController {
    @Autowired
    private LeaseAgreementService leaseAgreementService;

/**
 * 获取个人租约基本信息列表
 * 该方法通过GET请求获取当前用户的所有租约基本信息列表
 * 需要用户的身份令牌（access_token）作为请求头，以确定用户身份
 *
 * @param accessToken 用户身份令牌，用于验证用户身份
 * @return 包含租约基本信息列表的Result对象
 */
@Operation(summary = "获取个人租约基本信息列表")
@GetMapping("listItem")
public Result<List<AgreementItemVo>> listItem(@RequestHeader("access_token")String accessToken) {
    // 解析令牌以获取用户信息
    Claims claims = JwtUtil.parseToken(accessToken);
    // 从令牌中提取用户ID
    Integer userId = (Integer) claims.get("userId");
    // 使用用户ID获取租约列表
    List<AgreementItemVo> agreementItemVo = leaseAgreementService.customList(userId);
    // 返回包含租约列表的响应结果
    return Result.ok(agreementItemVo);
}


    @Operation(summary = "根据id获取租约详细信息")
    @GetMapping("getDetailById")
    public Result<AgreementDetailVo> getDetailById(@RequestParam Long id) {
        AgreementDetailVo agreementDetailVo =leaseAgreementService.customGetById(id);
        return Result.ok(agreementDetailVo);
    }

    @Operation(summary = "根据id更新租约状态", description = "用于确认租约和提前退租")
    @PostMapping("updateStatusById")
    public Result updateStatusById(@RequestParam Long id, @RequestParam LeaseStatus leaseStatus) {
        LeaseAgreement leaseAgreement=new LeaseAgreement();
        leaseAgreement.setId(id);
        leaseAgreement.setStatus(leaseStatus);
        boolean b = leaseAgreementService.updateById(leaseAgreement);
        if(!b){
            return Result.fail();
        }
        return Result.ok();
    }

    @Operation(summary = "保存或更新租约", description = "用于续约")
    @PostMapping("saveOrUpdate")
    public Result saveOrUpdate(@RequestBody LeaseAgreement leaseAgreement) {
        boolean b = leaseAgreementService.saveOrUpdate(leaseAgreement);
        if(!b){
            return Result.fail();
        }
        return Result.ok();
    }
}